﻿using eslib.DataRetrievalLib;
using System.Text;
using System.Threading.Tasks;

namespace eslib.nnp5.Matchers
{

    /// <summary>
    /// 简单json协议说明
    /// 本协议为嵌入式硬件使用
    /// 
    /// 支持【不包含内部对象的json描述字符串】，即json字符串中没有包含子对象(即没有'{'和'}'字符)
    /// 协议以Utf8编码
    /// 以'{'符号为包头， 以'}'符号为包尾
    /// </summary>
    public class SimpleJsonMatcher
    {
        /// <summary>
        /// 
        /// </summary>
        public SimpleJsonMatcher()
        {
            reset();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="b"></param>
        public void inStream(byte b)
        {
            //协议头部未接收
            if (!headRecived)
            {
                //如果收到'{'切换状态
                reset();        //重置stream
                if (b == '{')
                {
                    //包头也写入流
                    stream.write(b);
                    headRecived = true;        //匹配到包头
                }
            }

            //协议头部已接收
            else
            {
                //写入流,所有数据写入流
                stream.write(b);

                if (b == '}')      //匹配到包尾
                {
                    //通知
                    string json = Encoding.UTF8.GetString(stream.get());
                    SimpleJsonMatchEvent?.Invoke(json);

                    headRecived = false;    //下一轮
                }
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="buf"></param>
        public void inStream(byte[] buf)
        {
            for (int i = 0; i < buf.Length; i++) inStream(buf[i]);
        }



        /// <summary>
        /// 重置
        /// </summary>
        public void reset()
        {
            headRecived = false;
            stream.clear();
        }


        internal stream stream { get; private set; } = new stream();

        /// <summary>
        /// 状态值，已接收到包头时为true
        /// </summary>
        private bool headRecived = false;



        /// <summary>
        /// 接收到简单json协议时引发
        /// </summary>
        public event SimpleJsonMatchEventDelegate SimpleJsonMatchEvent;
    }

    /// <summary>
    /// 简单json协议触发委托
    /// </summary>
    /// <param name="json"></param>
    public delegate void SimpleJsonMatchEventDelegate(string json);
}
